#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <unistd.h>

namespace Client
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR
    };
    using namespace std;
    class tcpClient
    {
    public:
        tcpClient(const string &clientip, const uint16_t &clientport)
            : clientip_(clientip), clientport_(clientport), sockfd_(-1)
        {
        }
        void InitCient()
        {
            // 1.创建socket
            sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
            if (sockfd_ < 0)
            {
                std::cerr << "socket create error" << endl;
                exit(2);
            }
        }
        void run()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(clientport_);
            server.sin_addr.s_addr = inet_addr(clientip_.c_str());

            // 发起链接
            if (connect(sockfd_, (struct sockaddr *)&server, sizeof(server)) != 0)
            {
                std::cerr << "connect create error" << endl;
            }
            else
            {
                string msg;
                while (true)
                {
                    cout << "Enter# ";
                    getline(cin, msg);
                    write(sockfd_, msg.c_str(), msg.size());

                    char buffer [1024];
                    ssize_t n=read(sockfd_,buffer,sizeof(buffer)-1);
                    if (n>0)
                    {
                        buffer[n]=0;
                        cout<<"Server处理后为# "<<buffer<<endl;

                    }
                    else
                    {
                        break;
                    }
                    

                }
            }
        }
        ~tcpClient() {
            if(sockfd_>=0) close(sockfd_);
        }

    private:
        int sockfd_;
        uint16_t clientport_;
        string clientip_;
    };
}